class ApplicationController < ActionController::Base
  include MenusHelper
  include ApplicationHelper
  protect_from_forgery with: :exception
  before_action :check_login
  before_action :prepare_exception_notifier
  before_action :set_current_user

  helper_method :current_user, :request_referer

  def current_user
    return nil unless session[:user_id]
    @current_user ||= User.find_by_id(session[:user_id])
  end

  def check_login
    @action_start_time = Time.now
    if current_user.blank?
      respond_to do |format|
        format.html  {
          redirect_to '/login'
        }
        format.json {
          render :json => { 'error' => 'Access Denied' }.to_json
        }
      end
    end
  end

  def clear_session
    session[:user_id] = nil
  end

  def set_current_user
    Session.set_user current_user if current_user
  end


  def error_notice(msg)
    show_js_notice(msg, type: :error)
  end

  # 引用页
  def request_referer
    request.env['HTTP_REFERER'] || root_path
  end

  def show_js_notice(msg, arg = {})
    if arg[:type].to_s == 'error'
      if msg.is_a?(ApplicationRecord) && msg.errors.values.length>0
        _msg = "#{ts(:operation, :fail)}！<br/>#{msg.errors.full_messages.join('<br/>')}"
      end
      render js: "error_notice(#{(_msg||msg).to_json})"
    else
      flash[:notice] = msg
      respond_to do |format|
        format.html { redirect_to request_referer }
        format.js { render js: "Turbolinks.visit(#{(request_referer).to_json})"}
      end
    end
  end

  def prepare_exception_notifier
    h = { ip: request.ip, user_id: session[:user_id] }
    h.merge!(params: params.to_json ) rescue {}
    h.merge!(current_user: current_user.to_json(only: [:login, :name,:id, :school_ids])) if current_user
    request.env['exception_notifier.exception_data'] = h
  end
end
